/*
 * Parser.cpp
 *
 *  Created on: 2011-10-22
 *      Author: mateusz
 */

#include "Parser.h"

using namespace std;

// definiton (and declaration) of customers container and depot object
extern Depot* depot;
extern Customers* customers;

using namespace std;

Parser::Parser() {
	fileOpened = false;
}

Parser::~Parser() {
}

/**
 * opens load file and save it's descriptor to loadFileLink
 */
bool Parser::openLoadFile(string fileName) {
	if (loadFileLink == NULL) {
		// open file to read
		loadFileLink = fopen(fileName.c_str(), "r+");

		// check if file is open
		if (loadFileLink != NULL) {
			fileOpened = true;
			return true;
		}
	}
	return false;
}

/**
 * opens file to save and save it's descriptor to saveFileLink
 */
bool Parser::openSaveFile(string fileName) {
	if (saveFileLink == NULL) {
		// open file to read
		saveFileLink = fopen(fileName.c_str(), "w+");

		// check if file is open
		if (saveFileLink != NULL) {
			fileOpened = true;
			return true;
		}
	}
	return false;
}

void Parser::closeLoadFile() {
	if (loadFileLink != NULL) {
		fclose(loadFileLink);
		fileOpened = false;
	}
}

void Parser::closeSaveFile() {
	if (saveFileLink != NULL) {
		fclose(saveFileLink);
		fileOpened = false;
	}
}

/**
 * load data from given file
 */
bool Parser::loadData(string fileName, int maxCustomers) {
	string line;
	int customerId = 0, demand, vehicleCapacity, totalCustomers;
	double x, y, depotX, depotY;

	// open file if not opened yet && read is not from stdin
	if (fileName != "stdin") {
		if (!(this->openLoadFile(fileName))) {
			fprintf(stdout, "Cannot load data from %s\n", fileName.c_str());
			exit(1);
		}
	} else {
		loadFileLink = stdin;
	}

	//read customers number, vehicle capacity and depot description
	fscanf(loadFileLink, "%d%d", &totalCustomers, &vehicleCapacity);
	fscanf(loadFileLink, "%lf%lf", &depotX, &depotY);

	// how many of customers read
	totalCustomers = min(totalCustomers, maxCustomers);

	// create depot instance
	depot = new Depot(depotX, depotY, vehicleCapacity, totalCustomers);

	for (int i = 0; i < totalCustomers; i++) {
		//customerId++;
		fscanf(loadFileLink, "%lf%lf%d", &x, &y, &demand);

		customers->addCustomer(++customerId, x, y, demand);
	}

	if (fileName != "stdin") {
		this->closeLoadFile();
	}

	return true;
}

void Parser::startSaving(string fileName) {
	// open file if not opened yet && read is not from stdin
	if (fileName != "stdout") {
		if (!(this->openSaveFile(fileName))) {
			fprintf(stdout, "Cannot save data to %s\n", fileName.c_str());
			exit(1);
		}
	} else {
		saveFileLink = stdout;
	}
}

void Parser::stopSaving(string fileName) {
	if (fileName != "stdout") {
		this->closeSaveFile();
	}
}

FILE* Parser::getSaveFileLink() {
	return this->saveFileLink;
}
